package com.rchat.pocmini.db;

import android.content.ContentValues;
import android.content.Context;

import com.airtalkee.sdk.entity.AirMessage;
import com.rchat.pocmini.account.PocAccount;

import java.util.List;
import java.util.Map;

/**
 * Created by ljd on 2017/3/16.
 */

public class MessageDaoImpl extends BasePocDao implements MessageDao {

    protected static final String db_message = "t_message";

    public static class Creator implements BeanManager.Creator<MessageDaoImpl> {
        @Override
        public boolean isSingleton() {
            return true;
        }

        @Override
        public MessageDaoImpl create(Context context) {
            return new MessageDaoImpl(context);
        }
    }

    public static MessageDaoImpl get(Context context) {
        return BeanManager.get().getBean(MessageDaoImpl.class, context);
    }

    public MessageDaoImpl(Context context) {
        super(context);
    }

    @Override
    public List<AirMessage> loadMessageInfos(String sid, int currentPage, int pageSize) {
        String uid = PocAccount.getUserId();
        List<Map<String, String>> list = cursorToList(
                " SELECT * FROM t_message "
                        + " WHERE userid = ? AND sid = ? ORDER BY ID DESC LIMIT ?,?"
                , new String[]{uid, sid, (currentPage - 1) * pageSize + "", pageSize + ""});
//		List<Map<String,String>> list = cursorToList(
//				" SELECT * FROM t_message "
//				+ " WHERE userid = ? AND sid = ?"
//				, new String[]{uid, sid});
        List<AirMessage> retList = CollectionsHelper.newArrayList();
        for (int i = list.size() - 1; i >= 0; i--) {
            retList.add(parseMap2Info(list.get(i)));
        }
        return retList;
    }

    private AirMessage parseMap2Info(Map<String, String> m) {
        AirMessage info = new AirMessage();
        info.setMessageCode(m.get("msgId"));
        info.setSessionCode(m.get(""));
        info.setIpocidFrom(m.get("fromId"));
        info.setInameFrom(m.get("fromName"));
        info.setIphotoIdFrom(m.get("fromPhotoId"));
        info.setType(Integer.valueOf(m.get("type")));
        info.setCls(Integer.valueOf(m.get("typeSub")));
        info.setRecordType(Integer.valueOf(m.get("recordType")));
        info.setDate(m.get("dtDate"));
        info.setTime(m.get("dtTime"));
        info.setState(Integer.valueOf(m.get("state")));
        info.setBody(m.get("contentText"));
        info.setImageUri(m.get("contentRes"));
        info.setImageLength(Integer.valueOf(m.get("contentResLen")));
        return info;
    }

    @Override
    public AirMessage loadMessageInfo(String messageId) {
        String uid = PocAccount.getUserId();
        List<Map<String, String>> list = cursorToList(
                " SELECT * FROM t_channel "
                        + " WHERE userid = ? AND msgId = ?"
                , new String[]{uid, messageId});

        if (list.size() > 0) {
            return parseMap2Info(list.get(0));
        }
        return null;
    }

    @Override
    public void deleteMessage(String messageId) {
        String uid = PocAccount.getUserId();
        deleteDbData(db_message,
                "userid = ? AND msgId = ?",
                new String[]{uid, messageId});
    }

    @Override
    public void cleanMessageTabByUserId() {
        String uid = PocAccount.getUserId();
        deleteDbData(db_message,
                "userid = ?",
                new String[]{uid});
    }

    @Override
    public void cleanTable() {
        clearDbData(db_message);
    }

    @Override
    public void insertMessage(AirMessage message) {
        insertData(db_message, messageAppendBuild(message));
    }

    protected ContentValues messageAppendBuild(AirMessage message) {
        ContentValues localContentValues = new ContentValues();
        localContentValues.put("userid", PocAccount.getUserId());
        localContentValues.put("msgId", message.getMessageCode());
        localContentValues.put("sid", message.getSessionCode());
        localContentValues.put("fromId", message.getIpocidFrom());
        localContentValues.put("fromName", message.getInameFrom());
        localContentValues.put("fromPhotoId", message.getIphotoIdFrom());
        localContentValues.put("type", message.getType());
        localContentValues.put("typeSub", message.getCls());
        localContentValues.put("recordType", message.getRecordType());
        localContentValues.put("dtDate", message.getDate());
        localContentValues.put("dtTime", message.getTime());
        localContentValues.put("state", message.getState());
        localContentValues.put("contentText", message.getBody());
        localContentValues.put("contentRes", message.getImageUri());
        localContentValues.put("contentResLen", message.getImageLength());
        return localContentValues;
    }

    @Override
    public void updateMessage(AirMessage message) {
        String uid = PocAccount.getUserId();
        ContentValues cv = new ContentValues();
        cv.put("state", message.getState());

        updateDbData(db_message, cv,
                "userid = ? AND msgId = ?", new String[]{uid, message.getMessageCode()});
    }

    @Override
    public int getAllMessagesCount(String sid) {
        String uid = PocAccount.getUserId();
        List<Map<String, String>> list = cursorToList(
                " SELECT * FROM t_message "
                        + " WHERE userid = ? AND sid = ?"
                , new String[]{uid, sid});
        if (list.isEmpty()) {
            return 0;
        }
        return list.size();
    }

    @Override
    public List<AirMessage> loadPttMessageInfos(String sid, int currentPage, int pageSize) {
        String uid = PocAccount.getUserId();
        List<Map<String, String>> list = cursorToList(
                " SELECT * FROM t_message "
                        + " WHERE userid = ? AND sid = ? AND recordType = 1 ORDER BY ID DESC LIMIT ?,?"
                , new String[]{uid, sid, (currentPage - 1) * pageSize + "", pageSize + ""});
        List<AirMessage> retList = CollectionsHelper.newArrayList();
        for (Map<String, String> m : list) {
            retList.add(parseMap2Info(m));
        }
        return retList;
    }

    @Override
    public void batchInsertMessage(List<AirMessage> messages) {
        try {
            mDB.beginTransaction();
            for (AirMessage message : messages) {
                insertData(db_message, messageAppendBuild(message));
            }
            mDB.setTransactionSuccessful();
        } catch (Exception e) {
            useDbWhenCatchThrowable(e);
        } finally {
            mDB.endTransaction();
        }
    }

    @Override
    public List<AirMessage> loadPttMessageInfos(String sid, int offset) {
        String uid = PocAccount.getUserId();
        List<Map<String, String>> list = cursorToList(
                " SELECT * FROM t_message "
                        + " WHERE userid = ? AND sid = ? AND recordType = 1 ORDER BY ID DESC LIMIT ? OFFSET ?"
                , new String[]{uid, sid, 5 + "", offset + ""});//暂定5条
        List<AirMessage> retList = CollectionsHelper.newArrayList();
        for (Map<String, String> m : list) {
            retList.add(parseMap2Info(m));
        }
        return retList;
    }

}

